import { AnimationClip, Sprite, Animation, animation, SpriteFrame, log } from "cc";
import { StateMachine } from "./stateMachine";
import { sortSpriteFram } from "../utils";
import ResourceDir from "../scripts/runTime/resourceDir";

const ANIMATION_SPEED = 1 / 8;


/**
 * 1. 需要知道aimationClip
 * 2. 需要播放动画的能力animation
 */
export default class State {
   private animationClip: AnimationClip = null;

  constructor(
    private fsm: StateMachine,
    private path: string,
    private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal, 
  ) {
    this.init();
  }

  async init() {
    const promise = ResourceDir.Instance.loadDir(this.path);
    this.fsm._waitingList.push(promise);
    const spriteFrames = await promise;
    this.animationClip = new AnimationClip("aniClip");
    
    const track  = new animation.ObjectTrack(); // 创建一个向量轨道
    track.path = new animation.TrackPath().toComponent(Sprite).toProperty("spriteFrame"); // 指定轨道路径，即指定目标对象为 "Foo" 子节点的 "position" 属性
    const frames: Array<[number, SpriteFrame]> = sortSpriteFram(spriteFrames).map((item, index) => [ANIMATION_SPEED * index, item]);
    track.channel.curve.assignSorted(frames);

    // 最后将轨道添加到动画剪辑以应用
    this.animationClip.addTrack(track);
    this.animationClip.name = this.path;
    this.animationClip.duration = frames.length * ANIMATION_SPEED; // 整个动画剪辑的周期
    this.animationClip.wrapMode = this.wrapMode;
  }

  run(): void {
    if (this.fsm?._animationComponent.defaultClip?.name === this.animationClip.name) return;

    this.fsm._animationComponent.defaultClip = this.animationClip;
    this.fsm._animationComponent.play();
  }

}
